package cn.kkcxy.blog.system.factory.login.impl;

import cn.kkcxy.blog.common.constant.ExceptionMessageConstant;
import cn.kkcxy.blog.common.properties.LoginTypeKeysProperties;
import cn.kkcxy.blog.common.utils.RegionUtil;
import cn.kkcxy.blog.core.dto.client.LoginParamsDTO;
import cn.kkcxy.blog.core.entity.sys.SysUserLoginLog;
import cn.kkcxy.blog.core.enums.LoginTypeEnum;
import cn.kkcxy.blog.core.result.ResponseEntity;
import cn.kkcxy.blog.system.factory.login.LoginTypeHandler;
import cn.kkcxy.blog.system.service.sys.SysUserLoginLogService;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @BelongsProject: kkcxy-weblog
 * @BelongsPackage: cn.kkcxy.weblog.auth.server.handler.login
 * @Author: kkcxy
 * @CreateTime: 2024-07-19 20:26
 * @Description: 手机号登录处理
 * @Version: 1.0
 */
@Slf4j
@Component
public class PhoneTypeHandler implements LoginTypeHandler {

    /**
     * 读取所有对应类型存储的Key
     */
    @Resource
    private LoginTypeKeysProperties typeProperties;

    /**
     * 登录日志服务
     */
    @Resource
    private SysUserLoginLogService logService;


    /**
     * 对应处理的登录类型
     */
    @Override
    public LoginTypeEnum getHandlerType() {
        return LoginTypeEnum.PHONE;
    }

    /**
     * 登录类型处理的具体业务
     */
    @Override
    public Map<String, String> login(String code, LoginParamsDTO loginParamsDTO, String ip) {
        return null;
    }

    /**
     * 登录日志记录
     */
    @Async("asyncServerExecutor")
    @Override
    public void loginLogCreate(Long userId, Integer loginType, String message, Integer status, String ip) {
        // 根据ip地址获取地区
        String region = RegionUtil.getIpRegion(ip);
        // 构建实体
        SysUserLoginLog sysUserLoginLog =
                new SysUserLoginLog(null, userId, loginType, ip, region, message, status, null, 0);
        // 打印日志
        log.info("登录日志: {}", JSON.toJSONString(sysUserLoginLog));
        // 保存
        logService.save(sysUserLoginLog);
    }

    /**
     * 登录验证码获取的具体业务
     */
    @Override
    public ResponseEntity<Object> getCode(HttpServletResponse response, String account) {
        return ResponseEntity.fail(ExceptionMessageConstant.GET_VALID_CODE_ERROR);
    }
}
